package com.park.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.Base64.Decoder;

import org.apache.commons.collections.map.HashedMap;
import org.bouncycastle.crypto.tls.HashAlgorithm;

import com.park.model.Constants;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.sun.javafx.collections.MappingChange.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class FileUploadService {
	
	 public static String updateToMinio(String base64img) {
		 HashMap argMap=new HashMap();
		 argMap.put("data", base64img);
		 String url="http://111.229.173.104:8089/files/img/base64";		 
		 java.util.Map<String, Object> resultMap=HttpUtil.posts(url, argMap);
		 String resultString=(String) resultMap.get("body");
		 String aString=(String)JsonUtils.parseJSONMap(resultString).get("body");
		 return aString;
	 }

	public static String imgBase64Upload(String base64img) {
		Decoder decoder = Base64.getDecoder();
		// Base64解码
		byte[] imageByte = null;
		try {
			imageByte = decoder.decode(base64img);
			for (int i = 0; i < imageByte.length; ++i) {
				if (imageByte[i] < 0) {// 调整异常数据
					imageByte[i] += 256;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 生成文件名
		String files = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
				+ (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + ".png";
		// 生成文件路径
		String filename = Constants.UPLOADDIR + files;
		try {
			// 生成文件
			File imageFile = new File(filename);
			imageFile.createNewFile();
			if (!imageFile.exists()) {
				imageFile.createNewFile();
			}
			OutputStream imageStream = new FileOutputStream(imageFile);
			imageStream.write(imageByte);
			imageStream.flush();
			imageStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Constants.URL + files;

	}

	public static String put64image(String base64) throws Exception {
    	String ak = "7erPCrBonMkzzZc1wFZNJOSOe7mo6n_5dwB5fr0I";
        String sk = "lCwqANYjG_v76t8Yo0Edffw-ne_mXsVKSp1pj3vv";    // 密钥配置
        Auth auth = Auth.create(ak, sk);    // TODO Auto-generated constructor stub 
        String bucketname = "carpicture";    //空间名
        String key = new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".png";;    //上传的图片名
        Integer size= -1;
        String url = "http://upload.qiniup.com/putb64/" +size+"/key/"+ UrlSafeBase64.encodeToString(key);      
   //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, base64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1)))
                .post(rb).build();
        System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
        if(response.code() == 200 && response.message().equals("OK")) {
        	return "http://img.ninebit.cn/"+key;
        }else {
        	return null;
        }
    }
}
